package com.tuanzi.loan.workflow.schedule;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.settlement.CompanyInfo;
import com.tuanzi.loan.business.entity.workflow.ActHiProcinst;
import com.tuanzi.loan.business.service.settlement.CompanyInfoService;
import com.tuanzi.loan.business.service.workflow.ActHiProcinstService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.workflow.service.WorkflowProcessorService;
import com.tuanzi.server.loan_base.util.DateUtils;
import lombok.extern.log4j.Log4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * 甲方回数定  触发工作流定时器
 */
@Debug
@Log4j
@Service
@Transactional
public class SettlementDataBackScheduler {
    @Autowired
    private CompanyInfoService companyInfoService;
    @Autowired
    private WorkflowProcessorService workflowProcessorService;
    @Autowired
    private ActHiProcinstService actHiProcinstService;

    //获取所有审核通过的公司信息
    public List<CompanyInfo> getAuditPassCompanyInfo(){

        return companyInfoService.findCompaniesByAuditStatus(StatusEnum.AUDIT_PASS.getStatusId());
    }


    /**
     * 每周四启动工作流
     */
//    @Scheduled(cron ="${cron.settlement_data_back_activate_task_week}")
    public void activateWorkFlowByWeek(){
        List<CompanyInfo> auditPassCompanyList = getAuditPassCompanyInfo();

        //剔除月结的公司
       auditPassCompanyList = listWeekSettlementCompany(auditPassCompanyList);

       //剔除不开票的结算周期为预付的公司
        auditPassCompanyList = removeNoInvoiceCompany(auditPassCompanyList);

        if(auditPassCompanyList.size()>0){
            for (int i=0;i<auditPassCompanyList.size();i++){
                beginWorkFlowByAccount(auditPassCompanyList.get(i));
            }
        }
    }

    //每月8号激活工作流
//    @Scheduled(cron ="${cron.settlement_data_back_activate_task_month}")
    public void activateWorkFlowByMonth(){
        List<CompanyInfo> auditPassCompanyList = getAuditPassCompanyInfo();

        //剔除不开票的结算周期为预付的公司
//        auditPassCompanyList = removeNoInvoiceCompany(auditPassCompanyList);
        //剔除本月已经启动过工作流的公司
        auditPassCompanyList = removeIsCurrentMonthActivityCompany(auditPassCompanyList);

        if(auditPassCompanyList.size()>0){
            for (int i=0;i<auditPassCompanyList.size();i++){
                beginWorkFlowByAccount(auditPassCompanyList.get(i));
            }
        }
    }

    //剔除本月启动过工作流的公司
    public List<CompanyInfo> removeIsCurrentMonthActivityCompany(List<CompanyInfo> companyInfoList){
        String beginDate = DateUtils.getCurrentMonthFirstDate();
        String endDate = DateUtils.getCurrentMonthLastDate();

        List<ActHiProcinst> processList = actHiProcinstService.findActHiProcinstsByStartTimeGreaterThanEqualAndStartTimeIsLessThanEqualAndBusinessKeyStartsWith(
                DateUtils.formatYyyyMMddHHmmssToDate(beginDate + " 00:00:00"),
                DateUtils.formatYyyyMMddHHmmssToDate(endDate + " 23:59:59"), "DataBackProcess");

        Iterator<CompanyInfo> companyInfoIterator = companyInfoList.iterator();
        while (companyInfoIterator.hasNext()){
            CompanyInfo companyInfo = companyInfoIterator.next();
            for (ActHiProcinst actHiProcinst: processList) {
                if(("DataBackProcess:"+companyInfo.getId()).equals(actHiProcinst.getBusinessKey())){
                    companyInfoIterator.remove();
                    break;
                }
            }
        }

        return companyInfoList;
    }

    /**
     * 从公司列表中筛选出不是月结的公司
     * @param companyInfoList 公司筛选样本
     * @return 剔除月结公司的列表
     */
    public List<CompanyInfo> listWeekSettlementCompany(List<CompanyInfo> companyInfoList){
        Iterator<CompanyInfo> iterator = companyInfoList.iterator();
        while (iterator.hasNext()){
            CompanyInfo companyInfo = iterator.next();
            if(companyInfo.getSettlementPeroid() == StatusEnum.SETTLEMENT_MONTH.getStatusId()){
                iterator.remove();
            }
        }
        return companyInfoList;
    }

    /**
     * 从公司列表中剔除不开发票的、结算周期为预付的公司
     * @param companyInfoList 样本
     * @return
     */
    public List<CompanyInfo> removeNoInvoiceCompany(List<CompanyInfo> companyInfoList){
        Iterator<CompanyInfo> iterator = companyInfoList.iterator();
        while (iterator.hasNext()){
            CompanyInfo companyInfo = iterator.next();
            if(companyInfo.getIfInvoice() == false && companyInfo.getSettlementPeroid() ==  StatusEnum.SETTLEMENT_PREPAID.getStatusId()){
                iterator.remove();
            }
        }
        return companyInfoList;
    }

    /**
     *启动审核通过的公司的回数流程
     * @param companyInfo 公司信息
     */
    public void beginWorkFlowByAccount(CompanyInfo companyInfo){

        if(null!=companyInfo.getId()&& StringUtils.isNotBlank(companyInfo.getPrincipal())){
            Map<String,Object> nameMap=new HashedMap();
            nameMap.put("name",companyInfo.getPrincipal());
            workflowProcessorService.startProcess("xitongast","DataBackProcess","【"+companyInfo.getCompanyName()+"】回数流程",
                    Lists.newArrayList(String.valueOf(companyInfo.getId())), nameMap);
        }
    }

    enum StatusEnum{
        AUDIT_PASS(4,"审核通过"),
        SETTLEMENT_MONTH(3,"月结模式"),
        SETTLEMENT_PREPAID(4,"预付模式"),;

        private int statusId;
        private String detail;

        StatusEnum(int statusId, String detail) {
            this.statusId = statusId;
            this.detail = detail;
        }

        public int getStatusId() {
            return statusId;
        }

        public String getDetail() {
            return detail;
        }
    }
}
